var express = require('express');
require('mongoose-pagination');


var router = express.Router();

var md5 = require('md5');
var Comment = require('../SeModel/Comment');
router.all('*', function(req, res, next) {

    next();


});




//列表
router.get('/', function(req, res, next) {
    var id = req.query.id;
    var condition = {};

    if(id)
        condition = {parentid:id};
    console.log(id,condition);
    Comment.find(condition,function(err,data){
        return res.json(data);
    });


});
//创建

router.post('/create', function(req, res, next) {

    console.log(req.body);
    Comment.create(req.body,function(err,data){
        if(err)
        {
            var errors = Main.errorHelper(err);
            return res.json(errors);
        }
        else
        {
            return res.json({err:0,message:'操作成功',data:data});

        }



    });


});

//修改

router.post('/comment/update', function(req, res, next) {

    Comment.find({_id:req.query.id},function(err,data){
        if(err)
        {
            return res.json(err);
        }
        var model = data[0];

        model.name = req.body.name;
        model.article_id = req.body.article_id;
        model.content = req.body.content;
        model.updatetime = new Date();
        model.save(model,function(err,data){
            if(err)
            {
                var errors = Main.errorHelper(err);
                return res.json(errors);
            }
            else
            {
                if(req.body.ajax)
                {
                    return res.json({err:0,message:'操作成功',gourl:'/admin/articleCat'});
                }
                return  res.render('admin/articleCat/form',{title:'分类编辑',error:stringify(err),layout:'admin/layouts/admin'});
            }


        })

    })



});
//删除分类
router.get('/articleCat/delete', function(req, res, next) {

    var ArticleCat = require('../SeModel/ArticleCat');
    ArticleCat.find({_id:req.query.id},function(err,data){

        if(err)
        {
            return res.end(err);
        }
        var model = data[0];
        if(model)
        {
            var catid = model.catid;

            model.remove(function(err){
                console.log('remove');
                res.redirect('/admin/articleCat');
            });

        }else
        {
            res.redirect('/admin/articleCat');
        }

    })



});


module.exports = router;
